package com.major.binarysorttree;

public class Node {
    private int value;
    private Node leftNode;
    private Node rightNode;

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(Node leftNode) {
        this.leftNode = leftNode;
    }

    public Node getRightNode() {
        return rightNode;
    }

    public void setRightNode(Node rightNode) {
        this.rightNode = rightNode;
    }

    public Node(int value) {
        this.value = value;
    }

    public Node() {
    }

    // 中序遍历
    public void inoOrder() {
        if (leftNode != null) {
            leftNode.inoOrder();
        }
        System.out.println(this.toString());
        if (rightNode != null) {
            rightNode.inoOrder();
        }
    }

    // 添加
    public void add(Node node) {
        if (node == null) {
            return;
        }
        // 向左添加
        if (node.value < value) {
            if (leftNode == null) {
                leftNode = node;
            } else {
                leftNode.add(node);
            }
        }
        // 向右添加
        else {
            if (rightNode == null) {
                rightNode = node;
            } else {
                rightNode.add(node);
            }
        }
    }

    // 查找到要删除结点
    public Node search(int val) {
        if (val == value) {
            return this;
        } else if (val < value) {
            if (leftNode == null) {
                return null;
            }
            return leftNode.search(val);
        } else {
            if (rightNode == null) {
                return null;
            }
            return rightNode.search(val);
        }
    }

    // 找到要删除结点的父结点
    public Node searchParent(int val) {
        // 找到
        if (leftNode != null && leftNode.value == val || rightNode != null && rightNode.value == val) {
            return this;
        } else if (val < value && leftNode != null) {       // 想左递归查找
            return leftNode.searchParent(val);
        } else if (val > value && rightNode != null) {        // 向右递归查找
            return rightNode.searchParent(val);
        }
        // 没有找到
        else {
            return null;
        }
    }

    /*public void delete() {

    }*/
}
